//
//  ACAppointmentLiveViewController.m
//  ACLiteAVUISDK
//
//  Created by 冯琰琰 on 2021/3/29.
//

#import "ACAppointmentLiveViewController.h"
#import "ACAppointmentLiveCell.h"
#import "ACLiveModel.h"
#import "ACAnchorViewController.h"
#import "ACAnchorViewController+LiveDelegate.h"
#import "ACAudienceViewController.h"
#import "ACAudienceViewController+LiveDelegate.h"

@interface ACAppointmentLiveViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tableview;
@property(nonatomic,strong)NSMutableArray<ACLiveModel *>*dataArrayNoStart;
@property(nonatomic,strong)NSMutableArray<ACLiveModel *>*dataArrayStart;
@property(nonatomic,strong)NSMutableArray<ACBookedLiveModel *>*dataArrayOther;
@property(nonatomic,assign)int page;
@end

@implementation ACAppointmentLiveViewController
-(UITableView *)tableview{
    if (!_tableview) {
        _tableview = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.estimatedRowHeight = 109;
        _tableview.backgroundColor = UIColorFromRGB(0xF4F5F8);
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        NSBundle *curB = [NSBundle BundleWithBundleName:ACLiteAVUISDK targetClass:[self class] ];
        [_tableview registerNib:[UINib nibWithNibName:@"ACAppointmentLiveCell" bundle:curB] forCellReuseIdentifier:@"ACAppointmentLiveCell"];
    }
    return _tableview;
}
- (NSMutableArray<ACBookedLiveModel *> *)dataArrayOther{
    if (!_dataArrayOther) {
        _dataArrayOther = [NSMutableArray array];
    }
    return _dataArrayOther;
}
-(NSMutableArray<ACLiveModel *> *)dataArrayNoStart{
    if (!_dataArrayNoStart) {
        _dataArrayNoStart = [NSMutableArray array];
    }
    return _dataArrayNoStart;
}
- (NSMutableArray<ACLiveModel *> *)dataArrayStart{
    if (!_dataArrayStart) {
        _dataArrayStart = [NSMutableArray array];
    }
    return _dataArrayStart;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor cyanColor];
    self.page = 1;
    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    @weakify(self)
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        self.page = 1;
        [self requestData];
    }];
    self.tableview.mj_footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
        self.page += 1;
        [self requestData];
    }];
    [self.tableview.mj_header beginRefreshing];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.tableview.mj_header beginRefreshing];
}

-(void)requestData{
    [SVProgressHUD showWithStatus:@""];
    NSString *page = [NSString stringWithFormat:@"%d",self.page];
    dispatch_queue_t queue = dispatch_queue_create("requestData", 0);
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_async(queue, ^{
        [ACLiveRoomManager requestMyRoadShowWithPage:page success:^(id  _Nonnull responseObject) {
            NSArray *dataArr = [responseObject valueForKey:@"data"];
            if (self.page == 1) {
                [self.dataArrayNoStart removeAllObjects];
                self.dataArrayNoStart = [ACLiveModel mj_objectArrayWithKeyValuesArray:dataArr];
            }else{
                [self.dataArrayNoStart addObjectsFromArray:[ACLiveModel mj_objectArrayWithKeyValuesArray:dataArr]];
            }
            dispatch_semaphore_signal(semaphore);
        } failure:^(NSError * _Nonnull error) {
            [self.tableview.mj_header endRefreshing];
            [self.tableview.mj_footer endRefreshing];
            [SVProgressHUD dismiss];
        }];
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        [ACLiveRoomManager requesrBookListWithPage:page success:^(id  _Nonnull responseObject) {
            NSArray *dataArr = [responseObject valueForKey:@"data"];
            if (self.page == 1) {
                [self.dataArrayOther removeAllObjects];
                self.dataArrayOther = [ACBookedLiveModel mj_objectArrayWithKeyValuesArray:dataArr];
            }else{
                [self.dataArrayOther addObjectsFromArray:[ACBookedLiveModel mj_objectArrayWithKeyValuesArray:dataArr]];
            }
            dispatch_semaphore_signal(semaphore);
        } failure:^(NSError * _Nonnull error) {
            [self.tableview.mj_header endRefreshing];
            [self.tableview.mj_footer endRefreshing];
            [SVProgressHUD dismiss];
        }];
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableview.mj_header endRefreshing];
            [self.tableview.mj_footer endRefreshing];
            [SVProgressHUD dismiss];
            [self.tableview reloadData];
        });
    });
}
-(void)enterLiveRoomWithLiveID:(NSString *)liveID{
    ACAnchorViewController *anchorVC = [[ACAnchorViewController alloc] init];
    [self.navigationController pushViewController:anchorVC animated:YES];
    [anchorVC loginWithRoomID:liveID isAnchor:YES isOwner:YES callback:^(int code, NSString * _Nullable message) {
        
    }];
}
-(void)startLiveWithLiveID:(NSString *)liveID{
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要开始路演直播吗？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    @weakify(self)
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self)
        [ACLiveRoomManager requestModityWithLiveID:liveID Status:@"1" requestCallback:^(int code, NSString * _Nullable message) {
            if (code == 0) {
                [self enterLiveRoomWithLiveID:liveID];
            }
        }];
    }];
    [alertVC addAction:cancelAction];
    [alertVC addAction:sureAction];
    [self presentViewController:alertVC animated:YES completion:nil];
    
    
}
-(void)showAlert{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前预约的路演还未通过审核，如急需请联系管理员" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVC addAction:sureAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}

-(void)requeJoinLiveWithLiveID:(NSString *)liveID{
    // 观看
    [ACLiveRoomManager requestCheckAuthorityWithLiveID:liveID requestCallback:^(int code, NSString * _Nullable message) {
        if (code == 0) {
            ACAudienceViewController *VC = [[ACAudienceViewController alloc] init];
            [self.navigationController pushViewController:VC animated:YES];
            [VC loginWithRoomID:liveID callback:^(int code, NSString * _Nullable message) {
                
            }];
        }
    }];
}
#pragma mark - UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return self.dataArrayStart.count + self.dataArrayNoStart.count;
    }else{
        return self.dataArrayOther.count;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ACAppointmentLiveCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ACAppointmentLiveCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[ACAppointmentLiveCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ACAppointmentLiveCell"];
    }
    ACLiveModel *liveModel;
    if (indexPath.section == 0) {
        if (indexPath.row < self.dataArrayStart.count) {
            liveModel = self.dataArrayStart[indexPath.row];
        }else{
            liveModel = self.dataArrayNoStart[indexPath.row - self.dataArrayStart.count];
        }
        cell.model = liveModel;
    }else{
        ACBookedLiveModel *bookedLiveModel = self.dataArrayOther[indexPath.row];
        liveModel = bookedLiveModel.shows;
        cell.bookedModel = bookedLiveModel;
    }
    @weakify(self)
    cell.clickActionHandler = ^{
        @strongify(self)
        if (indexPath.section == 0) { // 自己的
            if ([liveModel.status intValue] == 0) {
                [self showAlert];
            }else if([liveModel.status intValue] == 3){// 进入直播间
                [self enterLiveRoomWithLiveID:liveModel.id_live];
            }else if ([liveModel.status intValue] == 1){
                [self startLiveWithLiveID:liveModel.id_live];
            }
        }else{
            [self requeJoinLiveWithLiveID:liveModel.id_live];
        }
    };
    return  cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 40)];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, self.view.bounds.size.width, 30)];
    titleLabel.text = section == 0 ? @"个人路演" : @"其他路演";
    titleLabel.font = [UIFont systemFontOfSize:16.0 weight:UIFontWeightMedium];
    titleLabel.textColor = UIColorFromRGB(0x303133);
    titleLabel.textAlignment = NSTextAlignmentLeft;
    [headerView addSubview:titleLabel];
    return headerView;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark - JXCategoryListContentViewDelegate
/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}
@end
